#include <stdio.h>
#include "fs.h"
#include "sector_node.h"
#include "fmt_prt.h"
#include "module.h"

static int32_t fat32_img_init_img(struct sector_list* list, uint32_t dsk_size, const char* path)
{
    FILE *fp;
    struct sector_node* node;
    uint32_t sector;
    uint32_t read;

    sector = 1;
    fp = fopen(path, "rb");
    if(!fp) {
        //
        fmt_printf("%s: %s fopen failed\n", __func__, path);
        return -1;
    }
    fmt_printf("%s: %s fopen success\n", __func__, path);

    while (!feof(fp))
    {
        node = alloc_sector_node(list, sector++);
        read = fread(node->data, list->sector_size, 1, fp);
        if(!read) break;
    }
    fmt_printf("%s: %s write to dsk finished\n", __func__, path);
    fclose(fp);
}

static struct fs_ops_struct fat32_img_ops = {
    .fs_sector_init_img = fat32_img_init_img,
    .fs_sector_init = NULL,
};

void init_fat32_img()
{
    struct fs_obj_struct* fs_obj;

    fs_obj = create_fs_obj();
    if(!fs_obj) {
        //
        fmt_printf("%s: create_fs_obj failed\n", __func__);
        return;
    }

    fs_obj->type = FAT32_IMG;
    fs_obj->ops = &fat32_img_ops;
    register_fs_obj(fs_obj);
}

module_init(init_fat32_img);